import { reactive, ref, onMounted, h, watch } from "vue";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import api from "@/api/seller/verify/spotcheck";
import { useRoute, useRouter } from "vue-router";
import { toNumber } from "@/api/_helpers";
export function use() {
  const formState = reactive({
    keyword: "",
    status: "",
    seller_verify_create: "",
    buyer_verify_create: "",
    page: 1,
    page_size: 10
  });

  const pagination = reactive({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    total: 0,
    align: "right",
    background: true,
    size: "default",
    layout: "total, sizes, prev, pager, next, jumper"
  });

  const dataList = ref([]);
  const loading = ref(true);
  const multipleSelection = ref([]);
  const route = useRoute();
  const router = useRouter();
  const hasProcessedInitialRoute = ref(false); // 添加标志位
  const handleSelectionChange = val => {
    multipleSelection.value = val;
  };

  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "状态",
      prop: "status",
      width: 100,
      slot: "status"
    },
    {
      label: "核实单号",
      prop: "verify_code",
      width: 250,
      align: "left",
      slot: "verify_code"
    },
    {
      label: "产品信息",
      width: 120,
      slot: "product"
    },
    {
      label: "采购数量",
      prop: "buyer_amount",
      width: 120
    },
    {
      label: "买家家备注",
      prop: "buyer_remark",
      minWidth: 120
    },
    {
      label: "核实数量",
      prop: "seller_amount",
      width: 120
    },
    {
      label: "价格信息",
      prop: "product.price",
      width: 150,
      slot: "price"
    },

    {
      label: "类型",
      prop: "type",
      width: 120,
      slot: "type"
    },
    {
      label: "申请时间",
      prop: "buyer_verify_create",
      width: 180
    },
    {
      label: "核实时间",
      prop: "seller_verify_create",
      width: 180
    }
  ];

  async function onSearch(eventOrReset: boolean | Event = true) {
    const resetPage = typeof eventOrReset === "boolean" ? eventOrReset : true;
    loading.value = true;
    if (resetPage) {
      formState.page = 1;
      pagination.currentPage = 1;
    }
    try {
      const params = {
        ...formState,
        page: formState.page,
        page_size: formState.page_size
      };

      const { data } = await api.fetch(params);
      const listData = Array.isArray(data.list) ? data.list : [];
      const pageInfo = (data.pagination ?? {}) as Record<string, any>;

      const resolvedPageSize = toNumber(
        pageInfo.pageSize ?? pageInfo.page_size,
        formState.page_size
      );
      const resolvedCurrentPage = toNumber(
        pageInfo.currentPage ?? pageInfo.current_page ?? pageInfo.page,
        formState.page
      );

      pagination.total = toNumber(pageInfo.total, listData.length);
      pagination.pageSize = resolvedPageSize;
      pagination.currentPage = resolvedCurrentPage;

      formState.page = resolvedCurrentPage;
      formState.page_size = resolvedPageSize;

      dataList.value = listData;
    } catch (error) {
      console.error("获取现货核实列表失败:", error);
    } finally {
      loading.value = false;
    }
  }

  function resetForm() {
    formState.keyword = "";
    formState.buyer_verify_create = "";
    formState.seller_verify_create = "";
    formState.status = "";
    formState.page = 1;
    formState.page_size = 10;

    pagination.currentPage = 1;
    pagination.pageSize = 10;

    onSearch();
  }

  function handleSizeChange(val) {
    pagination.pageSize = val;
    formState.page_size = val;
    handlePageChange(1);
  }

  function handlePageChange(val) {
    pagination.currentPage = val;
    formState.page = val;
    onSearch(false);
  }

  function openDialog(title = "现货核实", id = "") {
    import("../spotcheckForm.vue").then(module => {
      const form = module.default;
      let formRef = null;
      addDialog({
        title: `${title}`,
        props: { id },
        width: "60%",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        contentRenderer: () => {
          const formInstance = h(form, {
            id: id.toString(),
            visible: true,
            title: `${title}`,
            ref: ref => {
              formRef = ref;
            }
          });
          return formInstance;
        },
        beforeSure: done => {
          if (formRef && formRef.submitForm) {
            formRef.submitForm().then(success => {
              if (success) {
                done();
                onSearch();
              }
            });
          } else {
            done();
            onSearch();
          }
        }
      });
    });
  }
  if (route.query.verify_code && !hasProcessedInitialRoute.value) {
    hasProcessedInitialRoute.value = true;
    // 确保传递给 openDialog 的参数是字符串类型
    const verifyCode = Array.isArray(route.query.verify_code)
      ? route.query.verify_code[0]
      : route.query.verify_code;

    openDialog("现货核实", verifyCode);
  }
  onMounted(() => {
    onSearch();
  });

  return {
    form: formState,
    loading,
    columns,
    dataList,
    pagination,
    multipleSelection,
    onSearch,
    resetForm,
    handlePageChange,
    handleSizeChange,
    openDialog,
    handleSelectionChange
  };
}
